package com.zyt.fullcase.servlet;

import com.zyt.fullcase.domain.User;
import com.zyt.fullcase.service.UserService;
import com.zyt.fullcase.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理中文编码问题
        request.setCharacterEncoding("utf-8");

        // 获取参数
        String verifyCode = request.getParameter("verifycode");

        // 判断验证码是否正确
        String checkCoceServer = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
        if (verifyCode == null || checkCoceServer == null || !verifyCode.equalsIgnoreCase(checkCoceServer)) {
            // 验证码错误
            // 设置request域的错误信息
            request.setAttribute("errorMsg", "验证码错误");
            // 转发到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 调用Service验证用户名密码是否正确
        String userName = request.getParameter("user");
        String password = request.getParameter("password");
        UserService userService = new UserServiceImpl();
        User user = userService.getUser(userName, password);
        if (user == null) {
            // 设置request域的错误信息
            request.setAttribute("errorMsg", "用户名或者密码错误");
            // 转发到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 登录成功
        // 把User写入到Session
        request.getSession().setAttribute("user", user);
        // 转发到首页
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
